package com.o2opays.wechat.tool;

import com.o2opays.wechat.pojo.RepMess;
import com.o2opays.wechat.pojo.WeChatContent;
import com.o2opays.wechat.pojo.WeChatFinalValue;
import com.o2opays.wechat.pojo.WeChatOpenid;

import java.util.Map;

/**
 * Created by tugou on 2017/12/2.
 */
public class WeChatTool {
    /**
     * 页面授权，获取微信Openid
     * @param code
     * @return
     */
    public static WeChatOpenid getWeChatOpenid(String code){
        String url = WeChatFinalValue.ACCESS_OPENID_URL;
        url = url.replaceAll("APPID", WeChatContent.getInstance().getAppId());
        url = url.replaceAll("SECRET", WeChatContent.getInstance().getAppSecurt());
        url = url.replaceAll("CODE", code);
        String result = HttpClientUtil.doGet(url);
        Boolean isSuccess = checkRequestSucc(result);
        WeChatOpenid content;
        if(isSuccess){

            content = JsonUtil.toObject(result, WeChatOpenid.class);
        }else
        {
            RepMess mess = JsonUtil.toObject(result, RepMess.class);
            content = new WeChatOpenid();
            content.setMess(mess);
        }
        return content;
    }

    /**
     * 检查请求是否成功
     * @param content
     * @return
     */
    public static Boolean checkRequestSucc(String content) {
        Map<String, Object> map = JsonUtil.toObject(content, Map.class);
        if(!map.containsKey("errcode"))
            return true;
        Double errcode = (Double) map.get("errcode");
        if(errcode == 0)
            return true;
        return false;
    }
}
